import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { useUserStoreHook } from '@/store/modules/user'
import { invalidCode } from '@/dist/dist'
const cancelTokenSources = new Map()

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const userStore = useUserStoreHook()
    if (userStore.token) {
      config.headers.satoken = userStore.token
    }
    const source = axios.CancelToken.source()
    cancelTokenSources.set(source.token, source.cancel)
    config.cancelToken = source.token
    return config
  },
  (error: any) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response
    }
    const { code, msg } = response.data
    // token无效，重新登录
    if (invalidCode.includes(code)) {
      // 取消所有待响应请求
      for (const [token, cancel] of cancelTokenSources) {
        cancel(token)
      }
      // 提示重新登录
      ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
      }).then(() => {
        localStorage.clear()
        window.location.href = '/'
      })
    }

    // 正常数据返回
    if (code !== 200) {
      ElMessage.error(msg || '系统出错')
    }
    return response
  },
  (error: any) => {
    ElMessage.error(error.message || '系统出错')
    // 对错误请求特殊处理
    return Promise.resolve({
      data: {
        code: 500,
        msg: error.message,
      },
    })
  }
)

// 导出 axios 实例
export default service
